package com.cn.socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * &#064;Time 2024 八月 星期四 22:07
 *
 * @author ShangGuan
 */
public class HttpSocket implements Runnable {

    private final Socket socket;

    public HttpSocket(Socket socket) {
        this.socket = socket;
    }


    public HttpSocket socketProcess() throws IOException {
        System.out.println("Client connected");
        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder requestBuilder = new StringBuilder();
        String line;
        int contentLength = 0;

        // 读取请求头
        while ((line = reader.readLine()) != null && !line.isEmpty()) {
            requestBuilder.append(line).append("\r\n");

            // 查找 Content-Length 头以确定请求体的长度
            if (line.startsWith("Content-Length:")) {
                contentLength = Integer.parseInt(line.split(":")[1].trim());
            }
        }

        // 如果有请求体，读取请求体
        StringBuilder body = new StringBuilder();
        if (contentLength > 0) {
            char[] bodyChars = new char[contentLength];
            reader.read(bodyChars, 0, contentLength);
            body.append(bodyChars);
        }

        // 输出完整的请求信息
        System.out.println("Complete request data: \r\n" + requestBuilder.toString());
        if (body.length() > 0) {
            System.out.println("Request body: \r\n" + body.toString());
        }

        // 发送响应
        try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)) {
            outputStreamWriter.write("HTTP/1.1 200 OK\r\n");
            outputStreamWriter.write("Content-Type: text/plain\r\n");
            outputStreamWriter.write("Connection: close\r\n");
            outputStreamWriter.write("\r\n");
            outputStreamWriter.write("Request received successfully");
            outputStreamWriter.flush();
        }
        return this;
    }

    @Override
    public void run() {

    }
}
